package com.briup.ch12;

/**
 * @author yuxi
 * @version 1.0
 * @date 2025/10/20
 * @Description:
 */
import java.io.*;
import java.net.*;
import java.util.Scanner;

public class ChatClient {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("localhost", 8888);
        System.out.println("连接聊天室成功");

        // 输入用户名并发送
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入用户名：");
        String name = sc.nextLine();
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        out.println(name);

        // 启动线程接收消息
        new Thread(() -> {
            try {
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(socket.getInputStream()));
                String msg;
                while ((msg = in.readLine()) != null) {
                    System.out.println(msg); // 打印收到的消息
                }
            } catch (IOException e) {
                System.out.println("已断开连接");
            }
        }).start();

        // 主线程发送消息
        System.out.println("输入消息发送（输入exit退出）：");
        String msg;
        while ((msg = sc.nextLine()) != null) {
            out.println(msg);
            if ("exit".equals(msg)) break;
        }
        socket.close();
    }
}
